const express = require('express');
const app = express();
const qs = require('querystring');
const axios = require('axios');
const fs=require('fs');
const {Face} = require('../../model/face');


module.exports = async (req, res) => {
    async function matchPerson(personVerifyImg, personContrast) {
        const param = [
            {
                "image": personVerifyImg,
                "image_type": "BASE64",
                "face_type": "LIVE",
                "quality_control": "NORMAL",
                "liveness_control": "HIGH"
            },
            {
                "image": personContrast,
                "image_type": "BASE64",
                "face_type": "IDCARD",
                "quality_control": "NORMAL",
                "liveness_control": "NORMAL"
            }

        ];
        return new Promise((reslove, reject) => {
            axios(
                {
                    url: person,
                    method: "post",
                    header: {
                        "Content-Type": "application/json"
                    },
                    data: param
                },
            ).then(data => {
                reslove(data.data)
            }).catch(err => {
                reject(err)
            });
        })

    }

    
// 设置APPID/AK/SK
const APP_ID = "24637433";
const API_KEY = "UEE1BaspBS7EHLD8RkWaqwe5";
const SECRET_KEY = "eWeklayC9xg4oPQMP8KRB455ICBDVpot";


const param = qs.stringify({
    'grant_type': 'client_credentials',
    'client_id': API_KEY,
    'client_secret': SECRET_KEY 
});

//  获取 access_token
async function  getAccess_token(){
    await new Promise((resolve,reject)=>{
        app.get(
            {
                hostname: 'aip.baidubce.com',
                path: '/oauth/2.0/token?' + param,
                agent: false
            },
            function (res) {
                res.on('data', (d) => {
                    reject({
                        code:0,
                        msg:'success',
                        data:JSON.parse(d.toString()).access_token
                    })
                });
            }
        ).on('error', (e) => {
            resolve({
                code:1,
                msg:'network error',
                info:e,
                data:JSON.parse(d.toString()).access_token
            })
        });
    })
}

    let accessToken = await getAccess_token();
    let person ="https://aip.baidubce.com/rest/2.0/face/v3/match?access_token=" +accessToken;
    let face = Face.findOne({req.body.imagURL});
    try {
        await matchPerson(req.body.imagURL, face).then(data => {
            res.body = data
        }).catch(err => {
           res.body = err
        })
    } catch (err) {
        res.body = err
    }
}
